package com.imyuanma.qingyun.common.config.security;

import com.imyuanma.qingyun.interfaces.ums.model.LoginUserDTO;
import com.imyuanma.qingyun.interfaces.ums.service.IUmsPermissionsOutService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Spring Security UserDetailsService 实现
 *
 * @author wangjy
 * @date 2022/07/09 15:27:15
 */
@Service
public class DefaultUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(DefaultUserDetailsServiceImpl.class);
    /**
     * 权限服务
     */
    @Autowired
    private IUmsPermissionsOutService permissionsOutService;
    /**
     * 根据用户名获取用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUserDTO loginUserDTO = permissionsOutService.getByAccount(username);
        if (loginUserDTO == null) {
            logger.warn("[DefaultUserDetailsServiceImpl] 根据账号={}查询用户信息返回空", username);
            throw new UsernameNotFoundException("账户不存在");
        }
//        if (!loginUserDTO.isEnabled()) {
//            logger.warn("[DefaultUserDetailsServiceImpl] 账号={}处于禁用状态,登录失败", username);
//            throw new DisabledException("当前账户处于禁用状态");
//        }
        return DefaultUserDetails.newInstance(loginUserDTO);
    }
}
